import btree4j.BTreeException;
import btree4j.Value;
import btree4j.template.*;
import btree4j.utils.io.FileUtils;

import java.io.*;
import java.util.List;
import java.util.Scanner;

public class InterActiveTest {

    private static File dataDir = new File("test_data_interactive");
    private static TemplateManager templateManager;
    private static TemplateDataOperator dataOperator;
    private static Scanner scanner = new Scanner(System.in);
    private static Long selectedTemplateId = null;

    public static void main(String[] args) {
        try {
            // 初始化测试环境
            if (dataDir.exists()) {
                deleteDir(dataDir); // 清理旧测试数据
            }
            dataDir.mkdirs();

            templateManager = new TemplateManager(dataDir);
            dataOperator = new TemplateDataOperator(templateManager);

            showMenu();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("测试失败: " + e.getMessage());
        }
    }

    private static void showMenu() throws IOException, BTreeException, ClassNotFoundException {
        boolean running = true;
        while (running) {
            System.out.println("\n===== BTree4j Interactive Test =====");
            System.out.println("1. 创建模板");
            System.out.println("2. 获取模板");
            System.out.println("3. 删除模板");
            System.out.println("4. 选中模板");
            System.out.println("5. 获取所有模板");
            System.out.println("6. 退出");
            System.out.print("请输入操作编号: ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    createTemplate();
                    break;
                case 2:
                    getTemplate();
                    break;
//                case 3:
//                    updateTemplate();
//                    break;
                case 3:
                    deleteTemplate();
                    break;
                case 4:
                    selectTemplate();
                    break;
                case 5:
                    getAllTemplates();
                    break;
                case 6:
                    running = false;
                    closeResources();
                    System.out.println("退出程序");
                    break;
                default:
                    System.out.println("无效的操作编号");
            }

            if (selectedTemplateId != null) {
                showDataMenu();
            }
        }
    }

    private static void showDataMenu() throws IOException, BTreeException, ClassNotFoundException {
        boolean dataRunning = true;
        while (dataRunning) {
            System.out.println("\n===== 数据操作菜单 =====");
            System.out.println("1. 插入数据");
            System.out.println("2. 查询数据（主键）");
            System.out.println("3. 查询数据（二级索引）");
            System.out.println("4. 更新数据");
            System.out.println("5. 删除数据");
            System.out.println("6. 返回主菜单");
            System.out.print("请输入操作编号: ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    insertData();
                    break;
                case 2:
                    queryByPrimarykey();
                    break;
                case 3:
                    queryBySecondaryIndex();
                    break;
                case 4:
                    updateData();
                    break;
                case 5:
                    deleteData();
                    break;
                case 6:
                    dataRunning = false;
                    break;
                default:
                    System.out.println("无效的操作编号");
            }
        }
    }

    private static void createTemplate() throws IOException, BTreeException {
        System.out.print("请输入模板名称: ");
        String templateName = scanner.nextLine();

        Template template = new Template(templateName);
        boolean addingColumn = true;
        while (addingColumn) {
            System.out.print("请输入列名（输入空格结束添加列）: ");
            String columnName = scanner.nextLine();
            if (columnName.trim().isEmpty()) {
                addingColumn = false;
                continue;
            }

            System.out.print("请输入列类型: ");
            String columnType = scanner.nextLine();

            System.out.print("是否为主键（y/n）: ");
            boolean isPrimaryKey = scanner.nextLine().equalsIgnoreCase("y");

            System.out.print("是否允许为空（y/n）: ");
            boolean isNullable = scanner.nextLine().equalsIgnoreCase("y");

            System.out.print("是否创建索引（y/n）: ");
            boolean isIndexed = scanner.nextLine().equalsIgnoreCase("y");

            Column column = new Column(columnName, columnType, isPrimaryKey, isNullable, isIndexed);
            template.addColumn(column);
        }

        long templateId = templateManager.createTemplate(template);
        System.out.println("模板创建成功，ID: " + templateId);
    }

    private static void getTemplate() throws IOException, BTreeException {
        System.out.print("请输入模板ID或名称: ");
        String templateInput = scanner.nextLine();

        long templateId;
        try {
            templateId = Long.parseLong(templateInput);
        } catch (NumberFormatException e) {
            Template template = templateManager.getTemplateByName(templateInput);
            if (template != null) {
                System.out.println("通过名称获取模板: " + template);
                return;
            } else {
                System.out.println("模板不存在");
                return;
            }
        }

        Template template = templateManager.getTemplate(templateId);
        System.out.println("通过ID获取模板: " + template);
    }

//    private static void updateTemplate() throws IOException, BTreeException {
//        System.out.print("请输入要更新的模板ID或名称: ");
//        String templateInput = scanner.nextLine();
//
//        long templateId;
//        try {
//            templateId = Long.parseLong(templateInput);
//        } catch (NumberFormatException e) {
//            Template template = templateManager.getTemplateByName(templateInput);
//            if (template == null) {
//                System.out.println("模板不存在");
//                return;
//            }
//            templateId = template.getId();
//        }
//
//        Template template = templateManager.getTemplate(templateId);
//        if (template == null) {
//            System.out.println("模板不存在");
//            return;
//        }
//
//        System.out.print("请输入新模板名称（留空不修改）: ");
//        String newName = scanner.nextLine();
//        if (!newName.trim().isEmpty()) {
//            template.setName(newName);
//        }
//
//        templateManager.updateTemplate(template);
//        System.out.println("模板更新成功");
//    }

    private static void deleteTemplate() throws IOException, BTreeException {
        System.out.print("请输入要删除的模板ID或名称: ");
        String templateInput = scanner.nextLine();

        long templateId;
        try {
            templateId = Long.parseLong(templateInput);
        } catch (NumberFormatException e) {
            Template template = templateManager.getTemplateByName(templateInput);
            if (template == null) {
                System.out.println("模板不存在");
                return;
            }
            templateId = template.getId();
        }

        templateManager.deleteTemplate(templateId);
        System.out.println("模板删除成功");
    }

    private static void selectTemplate() throws IOException, BTreeException {
        System.out.print("请输入模板ID或名称: ");
        String templateInput = scanner.nextLine();

        long templateId;
        try {
            templateId = Long.parseLong(templateInput);
        } catch (NumberFormatException e) {
            Template template = templateManager.getTemplateByName(templateInput);
            if (template == null) {
                System.out.println("模板不存在");
                return;
            }
            templateId = template.getId();
        }

        selectedTemplateId = templateId;
        System.out.println("已选中模板ID: " + templateId);
    }

    private static void insertData() throws IOException, BTreeException, ClassNotFoundException {
        if (selectedTemplateId == null) {
            System.out.println("请先选中模板");
            return;
        }

        Template template = templateManager.getTemplate(selectedTemplateId);
        if (template == null) {
            System.out.println("模板不存在");
            return;
        }

        TemplateDataRow dataRow = new TemplateDataRow(template);
        for (Column column : template.getColumns()) {
            System.out.print("请输入列[" + column.getName() + "]的值: ");
            String value = scanner.nextLine();
            dataRow.setColumnValue(column.getName(), value);
        }

        dataOperator.addData(selectedTemplateId, dataRow);
        System.out.println("数据插入成功");
    }

    private static void queryByPrimarykey() throws IOException, BTreeException, ClassNotFoundException {
        if (selectedTemplateId == null) {
            System.out.println("请先选中模板");
            return;
        }

        System.out.print("请输入主键值: ");
        String primaryKeyValue = scanner.nextLine();

        TemplateDataRow dataRow = dataOperator.getData(selectedTemplateId, primaryKeyValue);
        if (dataRow != null) {
            System.out.println("查询结果: " + dataRow);
        } else {
            System.out.println("未找到与主键值 " + primaryKeyValue + " 相关的数据");
        }
    }

    private static void queryBySecondaryIndex() throws IOException, BTreeException, ClassNotFoundException {
        if (selectedTemplateId == null) {
            System.out.println("请先选中模板");
            return;
        }

        System.out.print("请输入二级索引列名: ");
        String columnName = scanner.nextLine();

        System.out.print("请输入查询值: ");
        String value = scanner.nextLine();

        List<Value> results = templateManager.queryBySecondaryIndex(selectedTemplateId, columnName, new Value(value));
        System.out.println("查询结果: " + results);

        for (Value pkValue : results) {
            TemplateDataRow dataRow = dataOperator.getData(selectedTemplateId, pkValue);
            System.out.println("关联数据: " + dataRow);
        }
    }

    private static void updateData() throws IOException, BTreeException, ClassNotFoundException {
        if (selectedTemplateId == null) {
            System.out.println("请先选中模板");
            return;
        }

        System.out.print("请输入主键值: ");
        String primaryKeyValue = scanner.nextLine();

        TemplateDataRow dataRow = dataOperator.getData(selectedTemplateId, primaryKeyValue);
        if (dataRow == null) {
            System.out.println("数据不存在");
            return;
        }

        Template template = templateManager.getTemplate(selectedTemplateId);
        TemplateDataRow updatedRow = new TemplateDataRow(template);
        for (Column column : template.getColumns()) {
            System.out.print("请输入列[" + column.getName() + "]的新值（留空不修改）: ");
            String value = scanner.nextLine();
            if (!value.trim().isEmpty()) {
                updatedRow.setColumnValue(column.getName(), value);
            } else {
                updatedRow.setColumnValue(column.getName(), dataRow.getColumnValue(column.getName()));
            }
        }

        dataOperator.updateData(selectedTemplateId, updatedRow);
        System.out.println("数据更新成功");
    }

    private static void deleteData() throws IOException, BTreeException, ClassNotFoundException {
        if (selectedTemplateId == null) {
            System.out.println("请先选中模板");
            return;
        }

        System.out.print("请输入主键值: ");
        String primaryKeyValue = scanner.nextLine();

        dataOperator.removeData(selectedTemplateId, primaryKeyValue);
        System.out.println("数据删除成功");
    }

    private static void getAllTemplates() throws IOException, BTreeException {
        List<Template> allTemplates = templateManager.getAllTemplates();
        System.out.println("所有模板:");
        for (Template t : allTemplates) {
            System.out.println(t);
        }
    }

    private static void closeResources() throws IOException, BTreeException {
        templateManager.close();
        dataOperator = null;
    }

    // 递归删除测试目录
    private static void deleteDir(File dir) {
        File[] files = dir.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    deleteDir(f);
                } else {
                    f.delete();
                }
            }
        }
        dir.delete();
    }
}